package com.itcast.core;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * 用于解析配置
 *
 * 将所有bean标签封装成bean定义
 *
 * 注册到 核心beanFactory中
 *
 *
 * @作者 itcast
 * @创建日期 2020/10/10 15:30
 **/
public class XmlBeanDefinitionReader {
    // 需要核心beanFactory对象
    private final DefaultListableBeanFactory beanFactory;
    public XmlBeanDefinitionReader(DefaultListableBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }
    public void loadBeanDefinitions(String config){
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(config);
        SAXReader reader = new SAXReader();
        Document document;
        try {
            document = reader.read(inputStream);
        } catch (DocumentException e) {
            e.printStackTrace();
            throw new RuntimeException("加载配置文件失败 ==>" + e.getMessage());
        }
        // 得到根标签 beans
        Element rootElement = document.getRootElement();
        // 获取所有bean标签
        List<Element> beanList = rootElement.elements("bean");
        for (Element beanEle : beanList) {
            // 解析 beanDefinition
            BeanDefinition beanDefinition = parseBeanDefinition(beanEle);
            // 将 beanDefinition 注册到容器
            beanFactory.registryBeanDefinition(beanDefinition);
        }
    }

    public BeanDefinition parseBeanDefinition(Element beanEle){
        BeanDefinition beanDefinition = new BeanDefinition();
        String beanName = beanEle.attributeValue("id");
        String className = beanEle.attributeValue("class");
        String scope = beanEle.attributeValue("scope");
        beanDefinition.setBeanName(beanName);
        beanDefinition.setClassName(className);
        if(scope!=null && !"".equals(scope)){
            beanDefinition.setScope(scope);
        }
        List<Element> propertyList = beanEle.elements("property");
        for (Element propertyEle : propertyList) {
            Property property = new Property();
            String name = propertyEle.attributeValue("name");
            String ref = propertyEle.attributeValue("ref");
            String value = propertyEle.attributeValue("value");
            property.setName(name);
            property.setRef(ref);
            property.setValue(value);
            beanDefinition.getPropertyList().add(property);
        }
        return beanDefinition;
    }
}
